package com.newcoder.community.controller;

import com.newcoder.community.dao.DiscussPostMapper;
import com.newcoder.community.entity.*;
import com.newcoder.community.event.EventProducer;
import com.newcoder.community.service.*;
import com.newcoder.community.util.CommunityConstant;
import com.newcoder.community.util.CommunityUtil;
import com.newcoder.community.util.HostHolder;
import com.newcoder.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.swing.plaf.PanelUI;
import java.util.*;
import java.util.stream.Stream;

@Controller
@RequestMapping("/discuss")
public class DiscussPostController implements CommunityConstant {
    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private UserService userService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private LikeService likeService;
    @Autowired
    private EventProducer eventProducer;
    @Autowired
    private ElasticSearchService elasticSearchService;
    @Autowired
    private RedisTemplate redisTemplate;
    @RequestMapping(path = "/add",method = RequestMethod.POST)
    @ResponseBody
    public String addDiscussPost(String title,String content){
         User user = hostHolder.getUser();
         if(user==null){
             return CommunityUtil.getJsonString(403,"你还没有登录！");
         }
         DiscussPost post = new DiscussPost();
         post.setUserId(user.getId());
         post.setTitle(title);
         post.setContent(content);
         post.setCreateTime(new Date());
         discussPostService.addDiscussPost(post);

         //触发发帖事件
         Event event = new Event()
                 .setTopic(TOPIC_PUBLISH)
                 .setUserId(user.getId())
                 .setEntityType(ENTITY_TYPE_POST)
                 .setEntityId(post.getId());
         eventProducer.fireEvent(event);
         //计算帖子分数
          String key = RedisKeyUtil.getPostScoreKey();
          redisTemplate.opsForSet().add(key,post.getId());
         //报错的
         return CommunityUtil.getJsonString(0,"发布成功!");
    }
    @RequestMapping(path = "/detail/{id}",method = RequestMethod.GET)
    public String intoDiscussPost(Model model, @PathVariable("id") int id, Page page){
        User user = hostHolder.getUser();
//        if(user==null){
//            return "/login";
//        }
        DiscussPost post = discussPostService.findDiscussPostById(id);
        User userById = userService.findUserById(post.getUserId());
        model.addAttribute("user",userById);
        model.addAttribute("post",post);
        //查询帖子的赞
        long entityLikeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId());
        model.addAttribute("likeCount",entityLikeCount);
        int likeStatus = user==null?0:likeService.findEntityLikeStatus(user.getId(),ENTITY_TYPE_POST,post.getId());
        model.addAttribute("likeStatus",likeStatus);
        //完善评论的分页信息
        page.setLimit(5);
        page.setPath("/discuss/detail/"+id);
        page.setRows(post.getCommentCount());
        //评论：给帖子的评论
        //回复：给评论的评论
        List<Comment> commentsByEntity = commentService.findCommentsByEntity(ENTITY_TYPE_POST, post.getId(),
                page.getOffset(), page.getLimit());
        //评论的vo列表
        List<Map<String,Object>> commentVoList = new ArrayList<>();
        if(commentVoList!=null){
            for(Comment comment:commentsByEntity){
                //评论的vo
                 Map<String,Object>  map = new HashMap<>();
                 map.put("comment",comment);
                 User user1 = userService.findUserById(comment.getUserId());
                 map.put("user",user1);
                 entityLikeCount = likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, comment.getId());
                 likeStatus = user==null?0:likeService.findEntityLikeStatus(user.getId(),ENTITY_TYPE_COMMENT,comment.getId());
                 map.put("likeCount",entityLikeCount);
                 map.put("likeStatus",likeStatus);
                 //回复列表
                 List<Comment> replys = commentService.findCommentsByEntity(ENTITY_TYPE_COMMENT,
                         comment.getId(), 0, Integer.MAX_VALUE);
                 //声明vo列表
                List<Map<String,Object>> replyList = new ArrayList<>();
                if(replys!=null){
                    for(Comment reply:replys){
                        Map<String,Object> replyMap = new HashMap<>();
                        replyMap.put("reply",reply);
                        System.out.println(reply);
                        User userReply = userService.findUserById(reply.getUserId());
                        replyMap.put("user",userReply);
                        //回复的目标
                        User userTarget = reply.getTargetId() == 0 ? null : userService.findUserById(reply.getTargetId());
                        replyMap.put("target",userTarget);
                        entityLikeCount = likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, reply.getId());
                        likeStatus = user==null?0:likeService.findEntityLikeStatus(user.getId(),ENTITY_TYPE_COMMENT,reply.getId());
                        replyMap.put("likeCount",entityLikeCount);
                        replyMap.put("likeStatus",likeStatus);
                        replyList.add(replyMap);
                    }
                }
                map.put("replys",replyList);
                //回复数量
                int commentCount = commentService.findCommentCount(ENTITY_TYPE_COMMENT, comment.getId());
                map.put("count",commentCount);
                commentVoList.add(map);
            }
        }
        model.addAttribute("comments",commentVoList);
        return "/site/discuss-detail";
    }
    //置顶请求
    @RequestMapping(path = "/top",method = RequestMethod.POST)
    @ResponseBody
    public String setTop(int id){
        discussPostService.updateType(id,1);
        //触发发帖事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(id)
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);
        return CommunityUtil.getJsonString(0);
    }
    //加精请求
    @RequestMapping(path = "/wonderful",method = RequestMethod.POST)
    @ResponseBody
    public String setWonderful(int id){
        discussPostService.updateStatus(id,1);
        //触发发帖事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(id)
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);
        //计算帖子分数
        String key = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(key,id);
        return CommunityUtil.getJsonString(0);
    }
    //删除请求
    @RequestMapping(path = "/delete",method = RequestMethod.POST)
    @ResponseBody
    public String setDelete(int id){
        discussPostService.updateStatus(id,2);
        //触发删帖事件
        Event event = new Event()
                .setTopic(TOPIC_DELETE)
                .setUserId(id)
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);
        return CommunityUtil.getJsonString(0);
    }
}
